﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.JobCommand_工作中心;

namespace SmartProduction.Write.API.Application.CommandHandlers.JobCommandHandler_工作中心
{
    public class JobAddCommandHandler : IRequestHandler<JobAddCommand, APIResult<object>>
    {
        private readonly IBaseRepository<Job> jobRepository;
        private readonly IMapper mapper;
        private static int nextJobNodeNumber = 1;
        private static readonly object lockObject = new object();

        public JobAddCommandHandler(IBaseRepository<Job> jobRepository,IMapper mapper)
        {
            this.jobRepository = jobRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(JobAddCommand request, CancellationToken cancellationToken)
        {
            
            APIResult<object> result = new APIResult<object>();
            var model=mapper.Map<Job>(request);
            // 使用锁机制确保编号的唯一性和正确自增
            lock (lockObject)
            {
                model.JobNode = "Job" + nextJobNodeNumber++;
            }
            model.CreatedBy = 1;
            model.CreatedTime = DateTime.Now;
            model.IsDelete = 0;
            model.Status = 0;
            var i=jobRepository.AddAsync(model).Result;
            if (i > 0)
            {
                result.Code = APIEnums.添加成功;
                result.Msg = APIEnums.添加成功.ToString();
                result.data = i;
            }
            else
            {
                result.Code = APIEnums.添加失败;
                result.Msg = APIEnums.添加失败.ToString();
                result.data = i;
            }
            return await Task.FromResult(result);
        }
    }
}
